package com.woniuxy.project.campus.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project.campus.account.dto.PermissionByRoleId;
import com.woniuxy.project.campus.account.dto.ResourceDto;
import com.woniuxy.project.campus.account.dto.RoleNameByPemissionName;
import com.woniuxy.project.campus.account.dto.SelectPermissionByRoleIdDto;
import com.woniuxy.project.campus.account.mapper.AccountMapper;
import com.woniuxy.project.campus.account.mapper.RoleAccountMapper;
import com.woniuxy.project.campus.account.model.Account;
import com.woniuxy.project.campus.account.model.Permission;
import com.woniuxy.project.campus.account.mapper.PermissionMapper;
import com.woniuxy.project.campus.account.model.RoleAccount;
import com.woniuxy.project.campus.account.model.form.RedisKey;
import com.woniuxy.project.campus.account.redisClint.RedisUtil;
import com.woniuxy.project.campus.account.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project.campus.util.TokenTool;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年02月17日
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private RoleAccountMapper roleAccountMapper;
    @Override
    public List<ResourceDto> selectPermissionByUserId(Integer id) {
        List<Permission> permissionList = permissionMapper.selectPermissionByUserId(id, 0);
        // 循环遍历菜单，查询二级菜单
        List<ResourceDto> list = new ArrayList<>();
        for (Permission permission : permissionList) {
            ResourceDto resource = BeanUtil.toBean(permission, ResourceDto.class);
            list.add(resource);
            // 查询一级菜单下的二级菜单
            List<Permission> childrenPermission = permissionMapper.selectPermissionByUserId(id, permission.getId());
            List<ResourceDto> childrenResourceDtos = new ArrayList<>();
            for (Permission childPermission : childrenPermission) {
                ResourceDto childResource = BeanUtil.toBean(childPermission, ResourceDto.class);
                // 查询二级菜单下的三级菜单
                List<Permission> grandchildrenPermission = permissionMapper.selectPermissionByUserId(id, childPermission.getId());
                if (!grandchildrenPermission.isEmpty()) {
                    List<ResourceDto> grandchildrenResourceDtos = new ArrayList<>();
                    for (Permission grandchildPermission : grandchildrenPermission) {
                        ResourceDto grandchildResource = BeanUtil.toBean(grandchildPermission, ResourceDto.class);
                        grandchildrenResourceDtos.add(grandchildResource);
                    }
                    childResource.setChildren(grandchildrenResourceDtos);
                }
                childrenResourceDtos.add(childResource);
            }
            resource.setChildren(childrenResourceDtos);
        }
        String Listjson= JSONUtil.toJsonStr(list);
        redisUtil.set(RedisKey.userResourceKey(id),Listjson,60*60*24*3);
        return list;
    }

    @Override
    public List<SelectPermissionByRoleIdDto> selectPermissionByRoleId(String token) {
        // 解析token 获取用户id
        Integer id = TokenTool.getUserIdByToken(token);
        // 判断是否为超级管理员
        Account account = accountMapper.selectById(id);
        if (account == null) {
            throw new RuntimeException("用户不存在");
        }
        QueryWrapper<RoleAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", 1);
        queryWrapper.eq("account_id", id);
        RoleAccount roleAccount = roleAccountMapper.selectOne(queryWrapper);
        if (roleAccount == null) {
            throw new RuntimeException("无权限查看");
        }

        // 查询角色及其关联的权限信息
        List<RoleNameByPemissionName> list = permissionMapper.selectPermissionByRoleId();
        List<SelectPermissionByRoleIdDto> selectPermissionByRoleIdDtoList = new ArrayList<>();

        // 使用map来存储角色及其对应的权限列表
        Map<Integer, SelectPermissionByRoleIdDto> rolePermissionMap = new HashMap<>();

        for (RoleNameByPemissionName roleNameByPemissionName : list) {
            Integer roleId = roleNameByPemissionName.getRoleId();
            String roleName = roleNameByPemissionName.getRoleName();

            // 如果map中不存在该角色的DTO对象，则创建一个新的DTO对象并添加到map中
            if (!rolePermissionMap.containsKey(roleId)) {
                SelectPermissionByRoleIdDto selectPermissionByRoleIdDto = new SelectPermissionByRoleIdDto();
                selectPermissionByRoleIdDto.setRoleName(roleName);
                selectPermissionByRoleIdDto.setRoleId(roleId);
                selectPermissionByRoleIdDto.setPermissionByRoleIdList(new ArrayList<>());
                rolePermissionMap.put(roleId, selectPermissionByRoleIdDto);
            }
            // 创建新的权限对象并设置属性
            PermissionByRoleId permissionByRoleId = new PermissionByRoleId();
            permissionByRoleId.setResourceId(roleNameByPemissionName.getPermissionId());
            permissionByRoleId.setResourceName(roleNameByPemissionName.getPermissionName());
            permissionByRoleId.setParentId(roleNameByPemissionName.getParentId());

            // 添加权限对象到角色的权限列表中
            rolePermissionMap.get(roleId).getPermissionByRoleIdList().add(permissionByRoleId);
        }
        // 将map中的值转换为列表
        selectPermissionByRoleIdDtoList.addAll(rolePermissionMap.values());

        return selectPermissionByRoleIdDtoList;
    }
}
